package com.quanyan.api;/**
 * Created by Administrator on 2016/5/5.
 */

import com.quanyan.common.GlobalConstValue;
import com.quanyan.entity.Command;
import com.quanyan.entity.DoResultData;
import com.quanyan.entity.ParamStruct;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;

/**
 * AbstractCommand
 * description:
 *
 * @author chuntu tuchun168@163.com
 * @date 2016/5/5 18:18
 */
public abstract class AbstractCommand implements CmdInterface{
    private static final Logger log=Logger.getLogger(AbstractCommand.class);
    protected ParamStruct paramStruct;

    public AbstractCommand(ParamStruct paramStruct) {
        this.paramStruct = paramStruct;
    }

    @Override
    public void doHandle() throws Exception {

        if (!validate(paramStruct)) {
            return;
        }
        DoResultData doResultData = executeCommand();
        if(doResultData.getCommand()!=null)
            paramStruct.setCommand(doResultData.getCommand());
        //是否返回结果
        if(doResultData!=null&&doResultData.getCommand()!=null&&doResultData.isGoBak()){
            responseResult(paramStruct);
        }

    }

    public static void responseResult(ParamStruct paramStruct) {
        Channel channel = paramStruct.getChannel();
        channel.write(paramStruct.getCommand());

    }

    /**
     * 验证每个命令是否合法
     *
     * @param paramStruct
     * @return
     */
    private static boolean validate(ParamStruct paramStruct) {
        Command command = paramStruct.getCommand();
        // 如果头尾不对，则忽略命令
        if (!paramStruct.getCommand().getHead().equals(GlobalConstValue.HEAD)) {
            log.error(String.valueOf(command.getCmd()) + command.getCmd()
                    + "Command, data length " + command.statBytesCounts()
                    + " ,Command Structure Error, Please Check The Binary Data");
            return false;
        }

        return true;
    }

    /**
     * 不同的命令实现不同的业务处理.所有命令都重重载该方法,来实现不同的业务处理
     */
    protected abstract DoResultData executeCommand()
            throws Exception;
}
